package com.promis.party.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.promis.compat.StatusBarCompat;
import com.promis.crypto.digest.MD5Digest;
import com.promis.crypto.symmetric.PBECodeCipher;
import com.promis.okhttp.HttpJsonParams;
import com.promis.party.R;
import com.promis.party.helper.ContextHelper;
import com.promis.party.preference.AccountPreferences;
import com.promis.party.preference.UserPreferences;

import javax.crypto.SecretKey;

public class LoginActivity extends AppCompatActivity {

    private ContextHelper contextHelper;

    private EditText edtvAccount;
    private EditText edtvPassword;
    private TextView txtvSubmit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarCompat.translucentStatusBar(this);
        StatusBarCompat.blackTextStatusBar(this);
        setContentView(R.layout.activity_login);

        edtvAccount = (EditText) findViewById(R.id.activity_login_edtv_account);
        edtvPassword = (EditText) findViewById(R.id.activity_login_edtv_password);
        txtvSubmit = (TextView) findViewById(R.id.activity_login_btnv_submit);

        initData();
        initListener();
    }

    private void initData() {
        contextHelper = new ContextHelper(getBaseContext());
        edtvAccount.setText(AccountPreferences.getInstance(getBaseContext()).getAccount());
    }

    private void initListener() {

        txtvSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Intent intent = new Intent(getBaseContext(), MainActivity.class);
                    startActivity(intent);
                    finish();
                  //  httpLogin();
                } catch (Exception e) {
                    Toast.makeText(getBaseContext(), "密钥加密失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void httpLogin() throws Exception {
        String account = edtvAccount.getText().toString();
        String password = edtvPassword.getText().toString();

        HttpJsonParams params = new HttpJsonParams();
        params.add("account", account);

        MD5Digest md5 = MD5Digest.getInstance();
        PBECodeCipher cipher = PBECodeCipher.getInstance();
        byte[] md5Key = md5.digest(password.getBytes());

        byte[] salt = cipher.initSalt();
        SecretKey secretKey = cipher.toKey(account);

        byte[] data = cipher.encrypt(md5Key, secretKey, salt);

        String pwd = cipher.encryptBASE64(data);
        String ransalt = cipher.encryptBASE64(salt);
        params.add("password", pwd);
        params.add("ransalt", ransalt);
//        params.add("cid", PushManager.getInstance().getClientid(contextHelper.getContext()));

        UserPreferences.getInstance(getBaseContext()).remove();
        AccountPreferences.getInstance(getBaseContext()).remove();
        String url = contextHelper.getServiceUrl(R.string.login);
//        new HttpClient<JsonLogin>(getBaseContext()){
//
//            @Override
//            protected void onSuccess(JsonLogin result) {
//                User user = result.getUser();
//
//                if (user != null) {
//                    UserPreferences.getInstance(getBaseContext()).put(user);
//                    AccountPreferences.getInstance(getBaseContext()).put(user.getAccount(), user.getPassword(), user.getState());
//                }
//
//                //绑定别名
//                PushManager.getInstance().bindAlias(getBaseContext(), user.getId(), user.getId());
//
//                Tag[] tagParam = null;
//                //标签
//                if(AuthType.PERSONSTORE.getValue() == user.getAuthType()) {
//                    String[] tags = new String[] {PushType.PERSONSTORE.getExplain()};
//                    tagParam = new Tag[tags.length];
//
//                    for (int i = 0; i < tags.length; i++) {
//                        Tag t = new Tag();
//                        //name 字段只支持：中文、英文字母（大小写）、数字、除英文逗号和空格以外的其他特殊符号, 具体请看代码示例
//                        t.setName(tags[i]);
//                        tagParam[i] = t;
//                    }
//                }else if(AuthType.LICENSE.getValue() == user.getAuthType()) {
//                    String[] tags = new String[] {PushType.STORE.getExplain()};
//                    tagParam = new Tag[tags.length];
//
//                    for (int i = 0; i < tags.length; i++) {
//                        Tag t = new Tag();
//                        //name 字段只支持：中文、英文字母（大小写）、数字、除英文逗号和空格以外的其他特殊符号, 具体请看代码示例
//                        t.setName(tags[i]);
//                        tagParam[i] = t;
//                    }
//                }else if(AuthType.PUBLICWELFARE.getValue() == user.getAuthType()) {
//                    String[] tags = new String[] {PushType.ORGANIZE.getExplain()};
//                    tagParam = new Tag[tags.length];
//
//                    for (int i = 0; i < tags.length; i++) {
//                        Tag t = new Tag();
//                        //name 字段只支持：中文、英文字母（大小写）、数字、除英文逗号和空格以外的其他特殊符号, 具体请看代码示例
//                        t.setName(tags[i]);
//                        tagParam[i] = t;
//                    }
//                }
//                PushManager.getInstance().setTag(getContext(),tagParam,System.currentTimeMillis() +"");
//
//                Toast.makeText(getBaseContext(), result.getMsgContent(), Toast.LENGTH_SHORT).show();
//                Intent intent = new Intent(getContext(), MainActivity.class);
//                startActivity(intent);
//                LoginActivity.this.finish();
//            }
//
//            @Override
//            protected void onError(String errorMsg) {
//                Toast.makeText(getBaseContext(), errorMsg, Toast.LENGTH_SHORT).show();
//            }
//        }.postAsyn(url, params);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event){
        if(keyCode==KeyEvent.KEYCODE_BACK)
            return true;//不执行父类点击事件
        return super.onKeyDown(keyCode, event);//继续执行父类其他点击事件
    }
}
